<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use think\Db;
use think\Cache;
use think\Config;
use fast\Wechat;
require ROOT_PATH . '/extend/aliyun-oss/autoload.php';
use OSS\OssClient;
use app\common\trilateral\aliyun\VideoProduction;
use OSS\Core\OssException;
use app\index\controller\Aliyun;
class Digitalpeople extends Frontend
{
    protected $noNeedLogin = '*';
	protected $noNeedRight = '*';
	protected $token=SZR_TOKEN;
    public function szurl_status(){
         $videodataarry = Db::name('store_digitalpeople_ch')->field('*')->where("szurl_status=0 and szurl like '%hfcdn.lingverse.co%' ")->limit(5)->order("id desc")->select();
        foreach ($videodataarry as $key => $videodata){
            	// 防止并发
			if(Cache::get('szr_store_digitalpeople_szurl_' . $videodata['id']))
			{
				continue;
			}
			Cache::set('szr_store_digitalpeople_szurl_' . $videodata['id'], 1, 120);
            var_dump("id=".$videodata['id']);
            Db::name('store_digitalpeople_ch')->where("id=".$videodata['id'])->update(["szurl_status"=>1]);
            $img=$videodata['szurl'];
            $imgex = explode(".",$img);
            $suffix = end($imgex);

            $file = ROOT_PATH.'public/szrvideo/'.$videodata["id"]."_".time()."_".$key.'.'.$suffix;

            $dlfile = dlfile(cdnurl($img), $file);
        $fileName = sha1(date('YmdHis', time()) . uniqid()).uniqid() .'.mp4';
        	$ossClient = new OssClient(ALIYUN_KEYID, ALIYUN_SECRET, "https://oss-cn-shanghai.aliyuncs.com");
           $result = $ossClient->uploadFile(ALIYUN_BUCKET_STORE_SC, date('Y-m').'/'.$fileName, $file);
            $url_image=$result['info']['url'];
            if($url_image){
                $file_media=Db::name('file_media')->where("url='".$videodata["video_url"]."'")->find();
                Db::name('store_digitalpeople_ch')->where("id=".$videodata['id'])->update(["szurl_status"=>1,"szurl"=>$url_image,"szurl_bz"=>$videodata['szurl'],"szurl_image"=>$file_media['url_image']]);
                  if(file_exists($file)){
                      unlink($file);
                  }
            }
        }
    }
    public function index($id=0)
    {
        // 语音生成成功后开始处理timeline
        if(!empty($id)){
            
             $videodataarry = Db::name('store_digitalpeople')->field('*')->where("status=1 and id=".$id)->limit(20)->select();
        }else{
           
             $videodataarry = Db::name('store_digitalpeople')->field('*')->where("status=1")->limit(20)->select();
        }
         foreach ($videodataarry as $key => $videodata){
             
             	// 防止并发
			if(Cache::get('szr_store_digitalpeople_send_' . $videodata['id']))
			{
				continue;
			}
			Cache::set('szr_store_digitalpeople_send_' . $videodata['id'], 1, 120);
			 Db::name('store_digitalpeople')->where("id=".$videodata['id'])->update(["status"=>2]);
			var_dump("store_digitalpeople:".$videodata['id']);
			 try
            		{
            		    $video_audio=json_decode($videodata['video_audio'],true);
            		  foreach ($video_audio as $key_audio=>$value_audio){
            		        $insertdata=[];
            		      	$insertdata['parentid']=$videodata['id'];
            		      	$insertdata['store_id']=$videodata['store_id'];
            		      	$insertdata['packing_id']=$videodata['packing_id'];
            		      	$insertdata['profile_id']=$videodata['profile_id'];
            		      	$insertdata['qd_type']=$videodata['qd_type'];
            		      	$insertdata['voice']=$videodata['voice'];
            		      	$insertdata['skip_random']=$videodata['skip_random'];
            		      	$insertdata['video_text']=isset($value_audio['text'])?$value_audio['text']:'';
            		      	if($insertdata['packing_id']>0){
            		      	   $insertdata['pc_status']=1; 
            		      	}
            		    
            		      	$insertdata['video_audio']=isset($value_audio['url'])?$value_audio['url']:'';
            		      	$insertdata['video_url']=$videodata['video_url'];
            		      	$insertdata['title']=$videodata['title']."_".$key_audio;
            		      	$insertdata['addtime']=date("Y-m-d H:i:s",time());
            		      	Db::name('store_digitalpeople_ch')->insert($insertdata);
            		  }
            		   if($videodata['store_id']!=4335&&$videodata['store_id']!=4336){
            		       if($videodata['qd_type']==2){
            		            $this->template_text();
            		       }else{
            		            $this->template();
            		       }
            		      
            		  }else{
            		       $this->template_cs();
            		  }
            		  return 200;
            		    
            		}	catch (\Exception $e)
            		{
                        Db::name('store_digitalpeople')->where("id=".$videodata['id'])->update(["status"=>4,'msg'=>$e->getMessage()]);
                        return 200;
            		} 
         }
    }
    public function template($id=0)
    {
        
        if(!empty($id)){
	        $videodataarry = Db::name('store_digitalpeople_ch')->field('*')->where(" status=1 and id=".$id)->limit(1)->select();
	    }else{
	       $videodataarry = Db::name('store_digitalpeople_ch')->field('*')->where(" status=1 ")->limit(10)->select();
	      
	    }
        
          foreach ($videodataarry as $key => $videodata){
              var_dump("store_digitalpeople_ch:".$videodata['id']);
              
              // 防止并发
			if(Cache::get('szr_store_digitalpeople_ch_send_' . $videodata['id']))
			{
				continue;
			}
			Cache::set('szr_store_digitalpeople_ch_send_' . $videodata['id'], 1, 120);
			 Db::name('store_digitalpeople_ch')->where("id=".$videodata['id'])->update(["status"=>2]);
			 $header = [
                
                "Authorization: Bearer ".$this->token,
                "content-type: application/json",
                
            ];
            $send_data=[];
            $send_data['audio_url']=$videodata['video_audio'];
            $send_data['skip_random']=(int)$videodata['skip_random'];
            $send_data['video_url']=$videodata['video_url'];
            $send_data['title']="接口提交数字人_".$videodata['store_id'];
            $send_data=json_encode($send_data,JSON_NUMERIC_CHECK);
            var_dump($send_data);
			 $ret=dcurl(SZR_URL."/api/v1/hifly/task/create",'POST',$send_data,$header);
			 $ret=json_decode($ret,true);
			 var_dump($ret);
				$insertdata=[];
            				// var_dump($ret);
            			if($ret['code'] == 0)
                		{
                			    $insertdata = [
                                    'job_id'=>$ret['job_id'],
                                     'status'=>2,
                                ];
                                Db::name('store_digitalpeople_ch')->where(['id'=>$videodata['id']])->update($insertdata);
                		
                		}else{
                		     $insertdata = [
                                    'msg'=>$ret['message'],
                                     'status'=>4,
                                ];
                		    Db::name('store_digitalpeople_ch')->where(['id'=>$videodata['id']])->update($insertdata);
                		}
                            
          }
        
    }
     public function template_text($id=0)
    {
        
        if(!empty($id)){
	        $videodataarry = Db::name('store_digitalpeople_ch')->field('*')->where(" status=1 and id=".$id)->limit(1)->select();
	    }else{
	       $videodataarry = Db::name('store_digitalpeople_ch')->field('*')->where(" status=1 ")->limit(10)->select();
	      
	    }
        
          foreach ($videodataarry as $key => $videodata){
              var_dump("store_digitalpeople_ch:".$videodata['id']);
              
              // 防止并发
			if(Cache::get('szr_store_digitalpeople_ch_send_' . $videodata['id']))
			{
				continue;
			}
			Cache::set('szr_store_digitalpeople_ch_send_' . $videodata['id'], 1, 120);
			 Db::name('store_digitalpeople_ch')->where("id=".$videodata['id'])->update(["status"=>2]);
			 $header = [
                
                "Authorization: Bearer ".$this->token,
                "content-type: application/json",
                
            ];
            // $digitalpeople_packing_ch = Db::name('store_digitalpeople_packing_ch')->field('*')->where(" packing_id='".$videodata['packing_id']."' ")->find();
            if(!$videodata['voice']){
                $insertdata = [
                        'msg'=>'没有绑定音色',
                         'status'=>4,
                    ];
    		    Db::name('store_digitalpeople_ch')->where(['id'=>$videodata['id']])->update($insertdata);
            }else{
                $digitalpeople_packing_voice = Db::name('store_digitalpeople_voice')->field('*')->where(" voice='".$videodata['voice']."' ")->find();
                $send_voice_type=isset($digitalpeople_packing_voice['id'])?10:20;
            }
            $send_data=[];
            $send_data['voice_id']=(int)$videodata['voice'];
            $send_data['voice_type']=(int)$send_voice_type;
            $send_data['text']=$videodata['video_text'];
            $send_data['video_url']=$videodata['video_url'];
            $send_data['skip_random']=(int)$videodata['skip_random'];
            $send_data['title']="接口提交数字人_文本_".$videodata['store_id'];
            $send_data=json_encode($send_data,JSON_NUMERIC_CHECK);
            var_dump($send_data);
			 $ret=dcurl(SZR_URL."/api/v1/hifly/task/create",'POST',$send_data,$header);
			 $ret=json_decode($ret,true);
			 var_dump($ret);
				$insertdata=[];
            				// var_dump($ret);
            			if($ret['code'] == 0)
                		{
                			    $insertdata = [
                                    'job_id'=>$ret['job_id'],
                                     'status'=>2,
                                ];
                                Db::name('store_digitalpeople_ch')->where(['id'=>$videodata['id']])->update($insertdata);
                		
                		}else{
                		     $insertdata = [
                                    'msg'=>$ret['message'],
                                     'status'=>4,
                                ];
                		    Db::name('store_digitalpeople_ch')->where(['id'=>$videodata['id']])->update($insertdata);
                		}
                            
          }
        
    }
     public function template_cs($id=0)
    {
        if(!empty($id)){
	        $videodataarry = Db::name('store_digitalpeople_ch')->field('*')->where(" status=1 and id=".$id)->limit(1)->select();
	    }else{
	       $videodataarry = Db::name('store_digitalpeople_ch')->field('*')->where(" status=1 ")->limit(10)->select();
	      
	    }
        
          foreach ($videodataarry as $key => $videodata){
              var_dump("store_digitalpeople_ch:".$videodata['id']);
			 Db::name('store_digitalpeople_ch')->where("id=".$videodata['id'])->update(["status"=>2]);
			 $header = [
                
                "Authorization: Bearer ".$this->token,
                "content-type: application/json",
                
            ];

                            $insertdata = [
                                    'job_id'=>'555',
                                    //  'status'=>3,
                                ];
                		    Db::name('store_digitalpeople_ch')->where(['id'=>$videodata['id']])->update($insertdata);
          }
        
    }
    public function get_inspect($id=0){
    // 查询获取中的
	  if(!empty($id)){
	        $make_videos = Db::name('store_digitalpeople_ch')->field('*')->where(" status=2 and job_id<>'555' and id=".$id)->limit(1)->select();
	    }else{
	       $make_videos = Db::name('store_digitalpeople_ch')->field('*')->where(" status=2 and job_id<>'555'")->limit(5)->select();
	      
	    }
		if($make_videos)
		{
			foreach ($make_videos as $key => $make_video)
			{
	    	// 防止并发
			if(Cache::get('szr_get_store_digitalpeople_ch_send_' . $make_video['job_id']))
			{
				continue;
			}
			Cache::set('szr_get_store_digitalpeople_ch_send_' . $make_video['job_id'], 1, 30);
				try
				{
				
					 $header = [
                
                        "Authorization: Bearer ".$this->token,
                        "content-type: application/json",
                        
                    ];
                   
                     $params='{"job_id":'.$make_video['job_id'].'}';
                    var_dump($params);
        			 $response=dcurl(SZR_URL."/api/v1/hifly/task/inspect",'POST',$params,$header);
        			 var_dump($response);
        			 $response=json_decode($response,true);
				    $data=[];
				    if($response['code'] == 0)
				{
        					if($response['status'] == '3')
        					{
        					   
        					
        					
        						$data['status']       = 3;
        						$data['szurl']       = $response['video_Url'];
        			
        			
        					}
        						if($response['status'] == '4')
        					{
        						$data['status']       = 4;
        						$data['msg']       = $response['message'];
        			
        			
        					}
				    }else{
				        	$data['status']       = 4;
        					$data['msg']       = $response['message'];
				    }
					$data['update_time'] = date("Y-m-d H:i:s",time());
					Db::name('store_digitalpeople_ch')->where(['id' => $make_video['id']])->update($data);
					echo '视频剪辑-new数据获取成功';
				}
				catch (TeaUnableRetryError $e)
				{
					echo '数字人查询-new数据获取错误：' . $e->getMessage();
				}
			}
		}
		else
		{
			echo '---数字人查询-new数据暂无更新---';
		}
		$this->szurl_status();
		$this->get_inspect_cs();
    }
     public function get_inspect_cs($id=0){
    // 查询获取中的
	  if(!empty($id)){
	        $make_videos = Db::name('store_digitalpeople_ch')->field('*')->where(" status=2 and job_id='555' and id=".$id)->limit(1)->select();
	    }else{
	       $make_videos = Db::name('store_digitalpeople_ch')->field('*')->where(" status=2 and job_id='555'")->limit(5)->select();
	      
	    }
	   // var_dump(Db::name('store_digitalpeople_ch')->getLastSql());
	   
		if($make_videos)
		{
			foreach ($make_videos as $key => $make_video)
			{
				try
				{
				
					 $header = [
                
                        "Authorization: Bearer ".$this->token,
                        "content-type: application/json",
                        
                    ];
                     $params = ['job_id'=>$make_video['job_id']];
        			 //$response=dcurl("/api/v1/hifly/task/inspect",'POST',$params,$header);
        			 $response=[];
				     $response['status']=3;
				     $response['video_url']='https://jianjiyxq.oss-cn-shanghai.aliyuncs.com/2024-05/771678c3e79673d4593c85c62b4bbf2306186c2d6656d471e7fa9.mp4';
					if($response['status'] == '3')
					{
						$data['status']       = 3;
						$data['szurl']       = $response['video_url'];
			
			
					}
					else
					{
						Db::name('store_digitalpeople_ch')->where(['id' => $make_video['id']])->setInc('error_count');
						if($make_video['media_id'])
						{
							$data['status'] = 2;
						}
						if($make_video['error_count'] > 20)
						{
							// 错三次，直接失败
							$data['status'] = 4;
						}
					}
					$data['update_time'] = date("Y-m-d H:i:s",time());
					Db::name('store_digitalpeople_ch')->where(['id' => $make_video['id']])->update($data);
					echo '视频剪辑-new数据获取成功';
				}
				catch (TeaUnableRetryError $e)
				{
					echo '数字人查询-new数据获取错误：' . $e->getMessage();
				}
			}
		}
		else
		{
			echo '---数字人查询-new数据暂无更新---';
		}
    }
    
    public function send_audio($num,$text){
        
        $data=[];
        for ($i = 1; $i <= $num; $i++) {
             if(isset($text[$i-1])){
                 $data[]=$text[$i-1]['url'];
             }else{
                  $om=$i%count($text)-1;
                    if($om<0){
                        $om=count($text)-1;
                    }
                    if($om<0){
                        $om=0;
                    }
                 $data[]=$text[$om]['url'];
             }
        }
        return $data;
    }
    // 包装
    public function pc_template($id=0)
    {
        if(!empty($id)){
	        $videodataarry = Db::name('store_digitalpeople_ch')->field('*')->where(" pc_status=1 and status=3 and id=".$id)->limit(1)->select();
	    }else{
	       $videodataarry = Db::name('store_digitalpeople_ch')->field('*')->where(" pc_status=1 and status=3")->limit(100)->select();
	      
	    }
        
          foreach ($videodataarry as $key => $videodata){
              var_dump("store_digitalpeople_ch:".$videodata['id']);
              
              // 防止并发
			if(Cache::get('szr_store_digitalpeople_ch_send_pc_' . $videodata['id']))
			{
				continue;
			}
			Cache::set('szr_store_digitalpeople_ch_send_pc_' . $videodata['id'], 1, 120);
			 Db::name('store_digitalpeople_ch')->where("id=".$videodata['id'])->update(["pc_status"=>2]);
        // 处理包装结构
            $digitalpeople_packing_autiotext = Db::name('store_digitalpeople_packing')->field('audio_text')->where("id='".$videodata['packing_id']."'")->find();
            $digitalpeople_packing = Db::name('store_digitalpeople_packing_ch')->field('packing_text')->where("profile_id='".$videodata['profile_id']."' and store_id='".$videodata['store_id']."'")->find();
            $effect=[];
            $effect['AspectRatio']="9:16";
            $effect['AudioTracks']=[];
            // $effect['Version']=1;
            // $effect['SdkVersion']="4.11.6";
            
            
            $data=[];
            $data['MediaUrl']=$videodata['szurl'];
            $data['Effects']=json_decode($digitalpeople_packing_autiotext['audio_text'],true);
           
            $effect['VideoTracks'][0]['VideoTrackClips'][]=$data;
            $data=[];
            $digitalpeople_packing_text=json_decode($digitalpeople_packing['packing_text'],true);
            $effect['SubtitleTracks'][0]['SubtitleTrackClips']=$digitalpeople_packing_text;
            $effect['FECanvas']['Width']=253.125;
            $effect['FECanvas']['Height']=450;
            
            
            $timeline=json_encode($effect);
            $insertdata=[];
    			$insertdata['create_time']=time();
    			$insertdata['title']=$videodata['title'];
    			$insertdata['text']=$videodata['video_text'];
    			$insertdata['timeline']=$timeline;
    			$insertdata['ossnum']=1;
    			$insertdata['ossnumtype']=1;
    			$insertdata['project_id']='';
    			$insertdata['status']=1;
    			$insertdata['send_type']=1;
    			$insertdata['send_type_time']='';
    			$insertdata['type']=6;
    			$insertdata['parentid']=$videodata['parentid']."_szr";
    			$insertdata['parentid_ch']=$videodata['id']."_szr";
    			$insertdata['store_id']=$videodata['store_id'];
		     Db::name('cloud_video')->insert($insertdata);
		  $id = Db::name('cloud_video')->getLastInsID();
		  $Aliyun = new Aliyun();
		  $Aliyun->cloud_video_aliyun_send($id);
            


          }
    }
}